import { print, showError, showSuccess } from '../utils/sysFun';
import api from '../common/api';
import { query, submit, remove } from '../services/commonService';

export default {
  namespace: 'modalsModel',

  state: {},

  effects: {
    *query({ targetKey, payload, callback }, { call }) {
      print(JSON.stringify(payload), api[`${targetKey}Query`].url, 'modalsModel');
      const response = yield call(query, payload, targetKey);
      if (response) {
        if (response.success) {
          if (callback) callback(response.entity || {});
        } else {
          showError(api[`${targetKey}Query`], response);
        }
      }
    },
    *submit({ targetKey, payload, showResult = true, callback }, { call }) {
      print(JSON.stringify(payload), api[`${targetKey}Submit`].url, 'modalsModel');
      const response = yield call(submit, payload, targetKey);
      if (response) {
        if (response.success) {
          if (showResult) showSuccess(api[`${targetKey}Submit`]);
          if (callback) callback(response.entity || {});
        } else {
          showError(api[`${targetKey}Submit`], response);
        }
      }
    },
    *remove({ targetKey, payload, showResult = true, callback }, { call }) {
      print(JSON.stringify(payload), api[`${targetKey}Remove`].url, 'modalsModel');
      const response = yield call(remove, payload, targetKey);
      if (response) {
        if (response.success) {
          if (showResult) showSuccess(api[`${targetKey}Remove`]);
          if (callback) callback(response.entity || {});
        } else {
          showError(api[`${targetKey}Remove`], response);
        }
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    clear() {
      return {};
    },
  },
};
